package com.lihepeng.leecode.tree;

import org.junit.Test;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 二叉树的左视图
 * 头条面试题
 * 每一行一个数
 */
public class LeftViewSolution {
    public List<Integer> leftView(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode treeNode = queue.peek();
            for (int i = 0; i < queue.size(); i++) {
                if (i == 0) {
                    res.add(treeNode.val);
                    queue.poll();
                }
            }
            if (treeNode.left != null) {
                queue.add(treeNode.left);
            }

            if (treeNode.right != null) {
                queue.add(treeNode.right);
            }
        }

        return res;
    }

    public List<Integer> leftView01(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        queue.add(root);
        int size = 1;
        int child = 0;
        while (!queue.isEmpty()) {
            child = 0;
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                if (i == size - 1) {
                    res.add(poll.val);
                }
                if (poll.left != null) {
                    queue.add(poll.left);
                    child++;
                }
                if (poll.right != null) {
                    queue.add(poll.right);
                    child++;
                }
            }
            size = child;
        }

        return res;
    }

    @Test
    public void runTest() {
        TreeNode head = new TreeNode(0);
        TreeNode t1 = new TreeNode(1);
        TreeNode t2 = new TreeNode(2);
        TreeNode t3 = new TreeNode(3);
        TreeNode t4 = new TreeNode(4);
        TreeNode t5 = new TreeNode(5);
        head.left = t1;
        head.right = t2;
        t2.left = t3;
        t3.right = t4;
        /*List<Integer> list = this.leftView(head);
        System.out.println(list);*/
        List<Integer> list = leftView01(head);
        System.out.println(list);
    }
}
